/* jshint esversion: 6 */
$(document).ready(function() {
    var userName = "";
});
var rating = (function() {
    //点亮整颗星星
    var LightEntire = function(el, options) {
        this.$el = $(el);
        this.$item = this.$el.find('.rating-item');
        this.opts = options;
    };
    LightEntire.prototype.init = function() {
        this.lightOn(this.opts.num);
        if (!this.opts.readOnly) {
            this.bindEvent();
        }
    };
    LightEntire.prototype.lightOn = function(num) {
        num = parseInt(num);
        // var lightOn = function(index) {}
        this.$item.each(function(index) {
            if (index < num) {
                $(this).addClass('active');
            } else {
                $(this).removeClass("active");
            }
        });
    };
    LightEntire.prototype.bindEvent = function() {
        var self = this,
            itemLength = self.$item.length;
        self.$el.on('mouseover', '.rating-item', function() {
            var num = $(this).index() + 1;
            self.lightOn(num);
            (typeof self.opts.select === 'function') && self.opts.select.call(this, num, itemLength);
            self.$el.trigger('select', [num, itemLength]);
        }).on('click', '.rating-item', function() {
            self.opts.num = $(this).index() + 1;
            if (typeof self.opts.choosen === 'function') {
                self.opts.choosen.call(this, self.opts.num, itemLength);
            }
            self.$el.trigger('choosen', [self.opts.num, itemLength]);
        }).on('mouseout', function() {
            self.lightOn(self.opts.num);
        });
    };
    //点亮半颗星星
    var LightHalf = function(el, options) {
        this.$el = $(el);
        this.$item = this.$el.find('.rating-item');
        this.opts = options;
        this.add = 1;
    };
    LightHalf.prototype.init = function() {
        this.lightOn(this.opts.num);
        if (!this.opts.readOnly) {
            this.bindEvent();
        }

    };
    LightHalf.prototype.lightOn = function(num) {
        var count = parseInt(num),
            ishalf = count !== num;
        num = count;
        // var lightOn = function(index) {}
        this.$item.each(function(index) {
            if (index < num) {
                $(this).addClass('active').removeClass("half");
            } else {
                $(this).removeClass("active").removeClass("half");
            }
        });
        if (ishalf) {
            this.$item.eq(count).addClass("half").removeClass("active");
        }
    };
    LightHalf.prototype.bindEvent = function() {
        var self = this,
            itemLength = self.$item.length;
        self.$el.on('mousemove', '.rating-item', function(e) {
            var $this = $(this),
                num = 0;
            if (e.pageX - $this.offset().left < $this.width() / 2) {
                self.add = 0.5;
            } else {
                self.add = 1;
            }
            num = $this.index() + self.add;
            self.lightOn(num);
            (typeof self.opts.select === 'function') && self.opts.choosen.call(this, num, itemLength);
            self.$el.trigger('select', [num, itemLength]);
        }).on('click', '.rating-item', function(e) {
            var $this = $(this);
            self.opts.num = $this.index() + self.add;
            self.lightOn(self.opts.num);
            if (typeof self.opts.choosen === 'function') {
                self.opts.select.call(this, self.opts.num, itemLength);
            }
            self.$el.trigger('choosen', [self.opts.num, itemLength]);
        }).on('mouseout', function() {
            self.lightOn(self.opts.num);
        });
    };
    $.fn.extend({
        rating: function(num) {
            return this.each(function() {
                init(this, num);
            });
        }
    });
    //默认参数
    var defaults = {
        mode: 'lightEntire',
        num: 0,
        readOnly: true,
        select: function() {},
        choosen: function() {},
    };
    var mode = {
        'lightEntire': LightEntire,
        'lightHalf': LightHalf,
    };
    //初始化方法
    var init = function(el, options) {
        options = $.extend({}, defaults, options);
        if (!mode[options.mode]) {
            options.mode = 'lightEntire';
        }
        // new LightEntire(el, options).init();
        // new LightHalf(el, options).init();
        new mode[options.mode](el, options).init();
    };
    return {
        init: init
    };
})();
//封装一个获取分页数据并填充 分页 的函数 并绑定事件
var fillData = (function() {
    /**需要分页的数据加载
     * @param {String} tar 填充分页对象目标
     * @param {string} url ajax目标地址
     * @param {number} page 当前页数对象
     * @param {function} callback 回调函数
     * @param {obj} params ajax请求参数
     */
    var getJSONData = function(tar, url, callback, params, options) {
        this.$tar = $(tar);
        this.url = url;
        this.params = params;
        this.callback = callback;
        this.opts = options;
        // this.cache = catche;
        this.maxpage = 1;
    };
    getJSONData.prototype.init = function() {
        this.getData();
    };
    getJSONData.prototype.getData = function(page) {
        var self = this;
        if (page !== undefined) {
            self.params.page = page;
        } else {
            page = 2;
        }
        ajaxXHR('get', self.url, function(data) {
            if (data.code != "success") {

                $('.modal').modal('show');
                $('.modal-body').html(data.message);
            } else {
                self.callback(data);
                if (self.opts.maxpage == "orderList") {
                    self.maxpage = Math.ceil(data.data.orderList.count / self.params.limit);
                    console.log(self.maxpage);
                } else {
                    self.maxpage = Math.ceil(data.data.count / self.params.limit);
                }

                self.paging(self.maxpage, self.params.page);
                if (self.opts.ifBindEvent) {
                    self.bindEvent(self.maxpage, self.params.page);
                }
                self.bindPage(self.maxpage, self.params.page);
            }
        }, self.params, 'json');
    };
    //分页函数
    getJSONData.prototype.paging = function(maxpage, page) {
        var $tar = this.$tar;
        //页数大于7页需要省略部分页数
        console.log(page);
        if (maxpage - page > 6) {
            $tar.html('');
            let a = ' <li class="page active" data-value="' + page + '">' + page + '</li>';
            for (count = page; count < maxpage; count++) {
                if (count - page > 3 || maxpage - count < 3) {
                    a += '<div class="omit">...</div>';
                    a += '<li class="page" data-value="' + maxpage + '">' + maxpage + '</li>';
                    break;
                } else {
                    let s = count + 1;
                    a += ' <li class="page" data-value="' + s + '">' + s + '</li>';
                } // 保证一定页数正常显示
            }
            $tar.append(a);
        } else {
            if (page == 1 || maxpage > 6) {
                $tar.html('');
                let a = ' <li class="page active" data-value="' + page + '">' + page + '</li>';
                for (i = page; i < maxpage; i++) {
                    a += '<li class="page" data-value="' + (i + 1) + '">' + (i + 1) + '</li>';
                }
                $tar.append(a);
            }
        }
    };
    //绑定点击事件
    getJSONData.prototype.bindEvent = function(maxpage, page) {
        var self = this,
            $LastP = $('.lastPage'),
            $nextP = $('.nextPage');
        $page = $('.page');
        self.opts.ifBindEvent = false;
        $LastP.on('click', function() {
            // 如果按钮没有被disable
            if (page <= maxpage) {
                $nextP.removeClass("disable");
            }
            if (page == 1) {
                $LastP.addClass("disable");
                $('.modal').modal('show');
                $('.modal-body').html('已经是第一页！');
            }
            if (page > 1) {
                page--;
                self.params.page--;
                self.getData(page);
                if (maxpage - page > 5) {
                    self.paging(maxpage, page);
                }
                return page;
            }
        });
        $nextP.on('click', function() {
            // 如果按钮没有被disable
            if (page > 1) {
                $LastP.removeClass("disable");
            }
            if (page == maxpage) {
                $nextP.addClass("disable");
                $('.modal').modal('show');
                $('.modal-body').html('已经是最后一页！');
                return;
            }
            if (page < maxpage) {
                console.log(page);
                console.log(maxpage, page);
                self.params.page++;
                page++;
                self.getData(page);
                if (maxpage - page > 5) {
                    self.paging(maxpage, page);
                }
                $page.eq(page - 1).addClass("active").siblings().removeClass("active");
                return page;
            }
        });
        self.bindPage(maxpage, page)
    };
    getJSONData.prototype.bindPage = function(maxpage, page) {
        var self = this,
            $page = $('.page'),
            $LastP = $('.lastPage'),
            $nextP = $('.nextPage');
        $('.page').on('click', function() {
            page = parseInt(this.dataset.value);
            if (page == maxpage) {
                $nextP.addClass("disable");
            } else {
                $nextP.removeClass("disable");
            }
            if (page == 1) {
                $LastP.addClass("disable");
            } else {
                $LastP.removeClass("disable");
            }
            console.log(maxpage, page);
            if (maxpage - page > 5) {
                self.paging(maxpage, page);
            }
            self.getData(page);
            $(this).addClass("active").siblings().removeClass("active");
            return page;
        });
    };
    var defaults = {
        ifPaging: true,
        ifBindEvent: true,
        mode: 'getJSONData',
        callback: function(data) {
            $('.modal').modal('show');
            $('.modal-body').html('请重写回调方法！');
        },
        params: {},
    };
    // var mode = {
    //     'getJSONData': getJSONData,
    //     'getHTMLData': getHTMLData,
    // };
    var init = function(tar, url, callback, params, options) {
        options = $.extend({}, defaults, options);
        new getJSONData(tar, url, callback, params, options).init();
        // if (!mode[params.mode]) {
        //     params.mode = 'getJSONData';
        // }
        // new mode[params.mode](tar, url, callback, params).init();
    };
    return {
        init: init,
    };
})();

function fillCityInfo(dataC) {
    var cityItem = dataC.hot,
        cityContent = "",
        hotNavContent = "";
    for (let i = 0; i < cityItem.length; i++) {
        const e = cityItem[i];
        cityContent += '<li class="citylistitem"data-value="' + e.cityPinYin + '" data-name="' + e.cityName + '">' + e.cityName + '</li>';
        hotNavContent += '<li class="city" data-value="' + e.cityPinYin + '" data-name="' + e.cityName + '"><a class="dataInfo">' + e.cityName + '</a><div class="triangle"></div></li>'
    }
    $('.hotNav').html('');
    $('.cityMain.hot').html(''); // 将获取到的html元素插入
    $('.hotNav').append(hotNavContent);
    $('.cityMain.hot').append(cityContent); // 将获取到的html元素插入
    cityContent = "";
    cityItem = dataC.cityList;
    const cityInfoList = [cityItem.a, cityItem.b, cityItem.c, cityItem.e, cityItem.f, cityItem.g, cityItem.h, cityItem.j, cityItem.k, cityItem.l, cityItem.m, cityItem.n, cityItem.p, cityItem.q, cityItem.r, cityItem.s, cityItem.t, cityItem.w, cityItem.x, cityItem.y, cityItem.z]
    for (let i = 0; i < 5; i++) {
        cityInfo = cityInfoList[i];
        for (let i = 0; i < cityInfo.length; i++) {
            const e = cityInfo[i];
            cityContent += '<li class="citylistitem" data-value="' + e.cityPinYin + '" data-name="' + e.cityName + '">' + e.cityName + '</li>'
        }
    }
    $('.cityMain.A-F').html(cityContent);
    cityContent = "";
    for (let i = 5; i < 9; i++) {
        cityInfo = cityInfoList[i];
        for (let i = 0; i < cityInfo.length; i++) {
            const e = cityInfo[i];
            cityContent += '<li class="citylistitem" data-value="' + e.cityPinYin + '" data-name="' + e.cityName + '">' + e.cityName + '</li>'
        }
    }
    $('.cityMain.G-K').html(cityContent);
    cityContent = "";
    for (let i = 9; i < 14; i++) {
        cityInfo = cityInfoList[i];
        for (let i = 0; i < cityInfo.length; i++) {
            const e = cityInfo[i];
            cityContent += '<li class="citylistitem"data-value="' + e.cityPinYin + '" data-name="' + e.cityName + '">' + e.cityName + '</li>'
        }
    }
    $('.cityMain.L-Q').html(cityContent);
    cityContent = "";
    for (let i = 14; i < 18; i++) {
        cityInfo = cityInfoList[i];
        for (let i = 0; i < cityInfo.length; i++) {
            const e = cityInfo[i];
            cityContent += '<li class="citylistitem" data-value="' + e.cityPinYin + '" data-name="' + e.cityName + '" >' + e.cityName + '</li>'
        }
    }
    $('.cityMain.R-W').html(cityContent);
    cityContent = "";
    for (let i = 19; i < 21; i++) {
        cityInfo = cityInfoList[i];
        for (let i = 0; i < cityInfo.length; i++) {
            const e = cityInfo[i];
            cityContent += '<li class="citylistitem" data-value="' + e.cityPinYin + '" data-name="' + e.cityName + '" >' + e.cityName + '</li>'
        }
    }
    $('.cityMain.X-Z').html(cityContent);

}

function showCapthca(type) {
    let imgCaptcha = $('#imgCaptcha').val() // 获取图形验证码input的值
    let phone = $('#regCellPhoneNum').val() // 获取手机号input的值
    $.ajax(url + "/v1/sms/captcha/receive", {
            method: "GET", // GET请求
            dataType: "json", // 希望服务器返回json格式数据，并使ajax进行json解析
            data: {
                phone: phone,
                type: type,
                imgCaptcha: imgCaptcha
            }, // 按接口文档要求传参
            xhrFields: {
                withCredentials: true // 允许跨域名储存和访问cookie
            }
        })
        .done(function(data) {
            $('.modal').modal('show');
            $('.modal-body').html("您的验证码为：" + data.data.smsCaptcha);
        })
}

function getCaptcha() {
    $.ajax(url + "v1/img/captcha", {
            method: "get", // get请求
            dataType: 'html', // 当服务器发来html元素时，需要如此设置，使ajax进行html解析
            xhrFields: {
                withCredentials: true // 允许跨域名储存和访问cookie
            }
        })
        .done(function(data) { // 处理ajax成功的回调
            $('#captcha').html(data); // 将获取到的html元素插入
        })
}

function ifLoged() {
    // var userIcon = document.getElementById("userIcon");
    //已登陆
    if (localStorage.APISHoteltoken != undefined) {
        $(".notLogin").hide();
        $("#userTopInfo").css('display', "inline-block");
        //加载用户头像 姓名等相关信息
        // userIcon.src = url_file + localStorage.avatar;
        $(".userName").html(localStorage.APISHotelname);
    } else {
        $('.notLogin').css("display", "inline-block");
        $("#userTopInfo").hide();
    }
};